<template>
	<view>
	<view @click="toForum()">
		返回论坛页
	</view>
	<uni-combox label="标签" :candidates="allTag" placeholder="请选择对应的标签" emptyTips="新建该标签"
	v-model="selectTag">
		
	</uni-combox>
	<view >
		<input class="my-title" focus placeholder="标题" v-model="title" />
	</view>

	<view class="cu-form-group margin-top">
	  <textarea maxlength="-1" bindinput="textareaAInput" placeholder="写下你此刻的想法吧..." v-model="content"> </textarea>
	</view>
	<view class="cu-bar bg-white margin-top">
	  <view class="action">
		图片上传
	  </view>
	  <view class="action">
		{{images.length}}/9
	  </view>
	</view>
	<view class="cu-form-group">
	  <view class="grid col-3 grid-square flex-sub">
		<view class="bg-img" v-for="(image,index) in images" :key="index" @click="viewImage(image)">
		  <image :src="imageUrl+images[index]" mode="aspectFill"></image>
		  <view class="cu-tag bg-red" @click="deleteImg(index)" data-index="index">
			<text class="cuIcon-close"></text>
		  </view>
		</view>
		<view class="solids" @click="chooseImage()" v-if="length<=9">
		  <text class="cuIcon-cameraadd"></text>
		</view>
	  </view>
	</view>


	<button class="cu-btn block bg-black margin-tb-sm lg" 
		style="width:650rpx;margin-left:50rpx;margin-top;"  
		@click="pubForum">
		上传
	</button>

</view>
</template>

<script>
import { api } from "../../const";
import uniCombox from "@/components/uni-combox/uni-combox"
export default {
	  watch: {
		content(next) {
		  console.log(next);
		},
		selectTag(nowSelect){
			console.log(nowSelect);
		}
	  },
	 components: {
		 uniCombox
	 },
	   /**
		* 组件的初始数据
		*/
	   data(){ 
		   return{
			 imageUrl:this.$imageUrl,
			 length:9,  
			 imageLengthLimit:9,
			 //默认标签指向
			 index:1,
			 allTag:[],
			 allTagWithId:[],
			 imagesWithSuffix:[],
			 //帖子数据
			 images: [
					  // "c45ed91e35234078b64918739114fe7d.jpg",
					  // "f7e3339c150a462abdab0b68bdda5305.jpg",
					  // "f30a61e11fe048c2bd8bc43cb171a530.jpg",
					  // "e8b29c51764343eabad4153acd44dac8.jpg",
					  // "22ee93d8663a4e5b8dbf35b523c2cc35.png",
					  // "23e63659d8504fd99c82c667f98128ff.jpg",
					  // "ba5fb8827c0642abae99a1aa8697689b.jpg",
					  // "8d1bb2846b23417298f4104623e05699.jpg"
					 ],
			 content: '谢邀，年薪百万，刚下飞机。',
			 title:"时间管理达人",
			 selectTag:"",
			 // forumData:{
				 
			 // }
			}
	   },
	   methods:{
		   //跳到论坛页面
		   toForum(){
			   uni.switchTab({
			   	url: '/pages/forum/Forum'
			   
			   })
		   },
		   //发贴
		   async pubForum(){
			   var tagId;
			   //已经选择的标签没有存在的情况
			   console.log("外1");
			   console.log(this.selectTag);
			   console.log(this.allTag.indexOf(this.selectTag));
			   if(this.allTag.indexOf(this.selectTag) == -1){
				   console.log("准备新增标签");
				   var shabi = await this.addTag(this.selectTag);	
				   console.log(shabi);
					console.log("异步结束");
			   }
			   for (let i = 0;i<this.allTagWithId.length;i++ ) {
					if(this.allTagWithId[i].game === this.selectTag){
						tagId = this.allTagWithId[i].id;
					}
			   }
				uni.request({
						url:this.$websiteUrl+"/pubForum",
						method:"POST",
						data:{
							title:this.title,
							content:this.content,
							tag:tagId,
							pictures:this.imgArrToStr()
						},
						dataType:"json",
						header:{
							"Content-Type": "application/x-www-form-urlencoded",
							token:this.$getToken()
						},
						success:(res) => {
							console.log(res.data.msg);
					   }
					   
				   });
			   
		   },
		   //新增一个标签
		   addTag(tagName){
			    return new Promise((resolve, reject) => {
					uni.request({
						url: this.$websiteUrl + "/addTag",
						header: {
							token: this.$getToken()
						},
						data:{
							tag:tagName
						},
						success: (res) => {
							var ret = "success";
							if(res.data.code != -1){
								//只有标签名
								this.allTag.push(res.data.data.game);
								//标签名+id
								this.allTagWithId.push(res.data.data);
							}
							else{
								ret =res.data.msg;
							}
							resolve(ret);
							
						},
						fail:(err) =>{
							reject(err);
						}
					});
			    })

			   	
		   },
		   //将当前的数组转化为字符串形式
		   imgArrToStr(){
			   var imgArrStr = "";
			   for(let i = 0; i<this.images.length;i++){
				   if(imgArrStr == ""){
					   console.log(i+"is null");
					   imgArrStr = this.images[i];
				   }
				   else{
					   console.log(i);
					   console.log(imgArrStr);
					   imgArrStr =  imgArrStr+","+this.images[i];
				   }
			   }
			   return imgArrStr;
		   },
			//上传单张图片
			upimages(tempFilePath){
				var test;
				const uploadTask = uni.uploadFile({
					url:this.$websiteUrl+"/uploadPicture",
					header:{
						token:this.$getToken()
					},
					  filePath: tempFilePath,
					  name: 'photo',
					  success: (resp) =>{
						  //未解析成json对象
						  var respJSON= JSON.parse(resp.data);
						  if (this.images.length != 0) {
							  this.images= this.images.concat(respJSON.data);
						  } else {
							  this.images= respJSON.data;
						  }
						}
				
					});
				},
			
			//选择图片的同时上传图片
			chooseImage() {
			  uni.chooseImage({
				count: this.imageLengthLimit-this.images.length, //剩下可上传的图片数量
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: (res) => {
				  for(let i = 0; i<this.images.length;i++){
					  this.upimages(res.tempFilePaths[i]);
				 }
				
				}
			  });
			},
			//查看大图
			viewImage(image) {
				this.setPhotoWithSuffix();	
				
			  wx.previewImage({
				urls: this.imagesWithSuffix,
				current: this.imageUrl+image
			  });
			},
			//获取图片+链接前缀
			setPhotoWithSuffix(){
				this.imagesWithSuffix = [];
				for(let i = 1;i<this.images.length; i++){
					this.imagesWithSuffix.push(this.imageUrl+this.images[i]);
				}
			},
			//删除图片
			deleteImg(index) {
				   this.images.splice(index, 1);
				   console.log(this.images[index]);
				   uni.request({
						url:this.$websiteUrl+"/deletePicture",
						data:{
							photo:this.images[index]
						},
						header:{
							token:this.$getToken()
						},
						success:(res) => {
							console.log(res.data.msg);
					   }
				   });
			},
			//获取内容输入
			textareaAInput(e) {
			  this.content=e.detail.value;
			},
			//获取所有标签
			getAllTag() {
				uni.request({
					url: this.$websiteUrl + "/getAllGames",
					header: {
						token: this.$getToken(),
					},
					success: (res) => {
						console.log("getAllTag suc..");
						for(let i =0;i<res.data.data.length;i++){
							//只有标签名
							this.allTag.push(res.data.data[i].game);
							//标签名+id
							this.allTagWithId.push(res.data.data[i]);
						}
					}
				});
				
			}
		},
		onLoad() {
			this.getAllTag();
			console.log("onload ..")
			console.log(this.imgArrToStr()) ;
		}
				
	}
</script>

<style>
	@import url("./publish.css");
</style>
